<template>
  <div class="app-container">
    <!-- 左右布局 -->
    <div class="main-layout">
      <!-- 左侧布局 -->
      <div class="left-section">
        <!-- 上部：串口通信区 -->
        <div class="serial-panel">
          <h1>电子秤</h1>
          <div class="control-group">
            <button @click="connectPort" :disabled="isConnected">连接串口</button>
            <button @click="disconnectPort" :disabled="!isConnected">断开连接</button>
            <div class="input-box">
              <input
                v-model="inputData"
                placeholder="输入发送内容"
                :disabled="!isConnected"
              />
              <button @click="sendData" :disabled="!isConnected">开始测量</button>
            </div>
          </div>
          <div class="data-display">
            <div class="action-buttons">
              <button 
                @click="saveData" 
                :disabled="!tableData.length"
                class="save-btn"
              >
                保存数据
              </button>
              <button @click="clearOutput">清空数据</button>
              <button @click="deleteSelectedData" :disabled="!selectedRows.length">删除选定数据</button>
            </div>
            <pre>{{ outputData }}</pre>
          </div>
        </div>
        <!-- 下部：数据可视化区 -->
        <div class="chart-section">      
          <div class="chart-container" ref="chartContainer"></div>
        </div>
      </div>
      <!-- 右侧：数据表格区 -->
      <div class="right-panel">
        <h2>数据表格</h2>
        <table>
          <thead>
            <tr>
              <th>选择</th>
              <th>序号</th>
              <th>数据内容</th>
              <th>时间</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in tableData" :key="index">
              <td><input type="checkbox" v-model="selectedRows" :value="index"></td>
              <td>{{ index + 1 }}</td>
              <td>{{ item.data }}</td>
              <td>{{ item.timestamp }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import extend from "@/extension/bizappproject/app_wgjy/dianzicheng.jsx";
import { ref, defineComponent } from "vue";
export default {
  data() {
    return {
      // 串口通信数据
      port: null,
      isConnected: false,
      inputData: "",
      outputData: "",
      buffer: "",
      tableData: [],
      selectedRows: [],
      
      // 图表数据
      chartType: "line",
      chartInstance: null,
      chartData: {
        categories: [],
        values: [],
        values2: [],
        values3: [],
        values4: []
      }
    };
  },

  methods: {
    // 串口通信方法
    async connectPort() {
      if (!("serial" in navigator)) {
        alert("浏览器不支持Web Serial API");
        return;
      }
      try {
        this.port = await navigator.serial.requestPort();
        await this.port.open({ baudRate: 9600 });
        this.isConnected = true;
        this.readData();
      } catch (error) {
        alert("连接失败: " + error.message);
      }
    },

    async readData() {
      try {
        const reader = this.port.readable.getReader();
        const decoder = new TextDecoder();
        while (true) {
          const { value, done } = await reader.read();
          if (done) break;
          
          this.buffer += decoder.decode(value, { stream: true });
          const lines = this.buffer.split("\n");
          
          if (lines.length > 1) {
            for (let i = 0; i < lines.length - 1; i++) {
              const data = lines[i].trim();
              if (data) {
                this.outputData += data + "\n";
                this.tableData.push({
                  data: data,
                  timestamp: new Date().toLocaleString()
                });
                const numData = parseFloat(data) || 0;
                this.chartData.categories.push(new Date().toLocaleString());
                this.chartData.values.push(numData);
                this.chartData.values2.push(numData * 1.1);
                this.chartData.values3.push(numData * 0.9);
                this.chartData.values4.push(numData * 1.2);
                this.updateChartData();
              }
            }
            this.buffer = lines[lines.length - 1];
          }
        }
      } catch (error) {
        console.error("读取错误:", error);
      }
    },

    updateChartData() {
      if (this.chartInstance) {
        this.generateChart();
      }
    },

    // 图表方法
    generateChart() {
      if (!this.chartInstance) {
        this.chartInstance = echarts.init(this.$refs.chartContainer);
      }
      
      const option = {
        title: { text: "数据统计分析" },
        tooltip: {},
        legend: {
          data: ['原始数据', '数据 * 1.1', '数据 * 0.9', '数据 * 1.2']
        },
        xAxis: { data: this.chartData.categories },
        yAxis: {},
        series: [
          {
            name: '原始数据',
            type: this.chartType,
            data: this.chartData.values,
            itemStyle: {
              color: '#5470C6'
            }
          },
          {
            name: '数据 * 1.1',
            type: this.chartType,
            data: this.chartData.values2,
            itemStyle: {
              color: '#91CC75'
            }
          },
          {
            name: '数据 * 0.9',
            type: this.chartType,
            data: this.chartData.values3,
            itemStyle: {
              color: '#EE6666'
            }
          },
          {
            name: '数据 * 1.2',
            type: this.chartType,
            data: this.chartData.values4,
            itemStyle: {
              color: '#FFBC52'
            }
          }
        ]
      };
      
      this.chartInstance.setOption(option);
      window.addEventListener('resize', this.chartInstance.resize);
    },

    // 通用方法
    saveData() {
      const blob = new Blob([JSON.stringify(this.tableData, null, 2)], 
        { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `serial-data-${new Date().toISOString().slice(0,10)}.json`;
      a.click();
      URL.revokeObjectURL(url);
    },

    clearOutput() {
      this.outputData = "";
      this.tableData = [];
      this.chartData.categories = [];
      this.chartData.values = [];
      this.chartData.values2 = [];
      this.chartData.values3 = [];
      this.chartData.values4 = [];
      if (this.chartInstance) {
        this.generateChart();
      }
    },

    deleteSelectedData() {
      this.selectedRows.sort((a, b) => b - a);
      this.selectedRows.forEach(index => {
        this.tableData.splice(index, 1);
        this.chartData.categories.splice(index, 1);
        this.chartData.values.splice(index, 1);
        this.chartData.values2.splice(index, 1);
        this.chartData.values3.splice(index, 1);
        this.chartData.values4.splice(index, 1);
      });
      this.selectedRows = [];
      this.updateChartData();
    }
  },

  mounted() {
    this.generateChart();
  },

  beforeUnmount() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  }
};
</script>

<style>
.app-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 20px;
  background: #f5f7fa;
}

.main-layout {
  display: flex;
  gap: 20px;
  height: 100%;
}

.left-section {
  flex: 2;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.serial-panel {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
}

.chart-section {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.right-panel {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
}

h1, h2 {
  color: #333;
  margin-bottom: 15px;
}

.control-group, .query-controls, .chart-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.input-box {
  display: flex;
  flex: 1;
  gap: 10px;
}

input, select {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  background: #409EFF;
  color: white;
  cursor: pointer;
  transition: background 0.3s;
}

button:hover {
  background: #66b1ff;
}

button:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
}

.save-btn {
  background: #67C23A;
}

.save-btn:hover {
  background: #85ce61;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.data-display pre {
  background: #f9f9f9;
  padding: 10px;
  border-radius: 4px;
  height: 150px;
  overflow: auto;
  font-family: monospace;
}

.table-container {
  flex: 1;
  overflow: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px 15px;
  border: 1px solid #ebeef5;
  text-align: left;
}

th {
  background: #f5f7fa;
  position: sticky;
  top: 0;
}

tr:hover {
  background: #f5f7fa;
}

.chart-container {
  width: 100%;
  height: calc(100% - 60px);
  min-height: 300px;
}
</style>        